// index.js
const { formatTime } = require("../../utils/util")
const { getAreaList } = require("../../utils/arealist")
const QQMapWX = require('../../utils/qqmap-wx-jssdk.min')
let qqmapsdk
// 获取应用实例
const app = getApp()

Page({
  data: {
    nowTime: '',
    list: [],
    notice: '',
    show: false,
    city: '',
    areaList: {}
  },
  onLoad(option) {
    const _this = this
    // 取城市列表
    this.getCityList()
    // 定位当前城市
    this.getUserLoaction()
    let date = new Date()
    let nowDate = formatTime(date)
    _this.setData({
     nowTime: nowDate
    })
  },
  
  // 把今日油价，存入数据库
  setTodayOilPriceToDb(data) {
    const _this = this
    var city = _this.data.city.replace("省","").replace("市","");
    wx.request({
      url: 'https://zxh.mmkjsh.cn/modules/price/add', 
      data: {
        name:city,
        priceZero:data.p89,
        priceTwo:data.p92,
        priceFive:data.p95,
        priceEight:data.p98,
        priceO:data.p0
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success(res) {
       
      }
    })
  },
  
  // 取今日油价,从数据库取
  getTodayOilPriceFromDb: function (city) {
    const _this = this
    
 
  },
  // 取今日油价
  getTodayOilPrice: function () {
    const _this = this
    var city = _this.data.city.replace("省","").replace("市","").replace("自治区","").replace("壮族","").replace("回族","").replace("维吾尔","");
    wx.request({
      url: 'https://zxh.mmkjsh.cn/modules/price/list',
      data: {
        name:city
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        if(res.data.total == 1){
          var data = res.data.rows[0];
          _this.setData({
            list: [
              { title: '89', type: 1, price: data.priceZero, yesterday: '6.17' },
              { title: '92', type: 1, price: data.priceTwo, yesterday: '6.16' },
              { title: '95', type: 1, price: data.priceFive, yesterday: '6.52' },
              { title: '98', type: 1, price: data.priceEight, yesterday: '7.24' },
              { title: '0', type: 2, price: data.priceO, yesterday: '5.70' }
            ]
          })
       
        }else{
          wx.request({
            url: 'https://api.tianapi.com/oilprice/index', 
            data: {
              key:'0841cb93ed3b43ec4909ca3ff8992f15',
              prov:city
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success(res) {
              if(res.data.code == "200"){
                var data = res.data.newslist[0];
                console.log(res);
                _this.setData({
                  list: [
                    { title: '89', type: 1, price: data.p89, yesterday: '6.17' },
                    { title: '92', type: 1, price: data.p92, yesterday: '6.16' },
                    { title: '95', type: 1, price: data.p95, yesterday: '6.52' },
                    { title: '98', type: 1, price: data.p98, yesterday: '7.24' },
                    { title: '0', type: 2, price: data.p0, yesterday: '5.70' }
                  ]
                })
                _this.setTodayOilPriceToDb(data);
              }
              
            }
          })
        }
        
      }
    })
   
   
  },


  // 取城市列表
  getCityList: function () {
    this.setData({
      areaList: getAreaList()
    })
  },
  showCity: function () {
    this.setData({ show: true })
  },
  onClose: function () {
    this.setData({ show: false })
  },
  confirmChose: function (e) {
    this.setData({ city: e.detail.values[0]['name'], show: false })
     // 取今日油价
    this.getTodayOilPrice()
  },
  onShareAppMessage: function () {
    return {
      title: '今日油价查询',
      path: '/pages/index/index'
    }
  },
  // 获取用户当前位置
  getUserLoaction: function () {
    let vm = this
    wx.getSetting({
      success: (res) => {
        // console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        }
        else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        // console.log(JSON.stringify(res))
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  getLocal: function (latitude, longitude) {
    var _this =this
    qqmapsdk = new QQMapWX({
      key: '3RABZ-YPA3U-SN4V7-BILRL-OWZIQ-A2BPH'
    })
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        // console.log(JSON.stringify(res));
         let province = res.result.ad_info.province
        // let city = res.result.ad_info.city
        //let district = res.result.ad_info.district
        //console.log(district)
        vm.setData({
          city: province
        })
         // 取今日油价
        _this.getTodayOilPrice()
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  }
})
